package optimizations;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import execution.Interpretter;
import execution.Pair;
import execution.Tape;

import optimizations.parser.Parser;
import optimizations.parser.ParserFactory;
import optimizations.parser.SyntaxTree.AbstractSyntaxNode;

public class SyntaxTreeInterpretter implements Interpretter {
	
	private final List<AbstractSyntaxNode> tree;
	
	public SyntaxTreeInterpretter(String filename) throws FileNotFoundException {
		BufferedReader reader = new BufferedReader(new FileReader(filename));
		Parser parser = (ParserFactory.INSTANCE).newParser(reader);
		tree = parser.parse();
	}

	public Pair<String, Boolean> compute(InputStream is) {
		String out = "";
		try {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			Tape tape = new Tape(os, is);
			for (AbstractSyntaxNode node : tree) {
				node.execute(tape);
			}
			out = os.toString();
			return new Pair<String, Boolean>(out, new Boolean(true));
		} catch (IOException e) {
			System.out.println("c-brainfk encountered a error in receiving input from System.in!");
			return new Pair<String, Boolean>(out, new Boolean(false));
		}
	}

}
